package cn.wbnull.springbootdemo.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

import cn.wbnull.springbootdemo.model.Users;

import cn.wbnull.springbootdemo.utils.Catagory;
import cn.wbnull.springbootdemo.utils.easyutil;
import net.sf.json.JSONObject;
import cn.wbnull.springbootdemo.service.UserService;

/**
 * 功能描述
 *
 * @author EDZ
 * @since 2022-04-02
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //分页总数
    private static final int PAGE_SIZE = 30 ;
    //查询列表
    @GetMapping("/selectList")
    public List<Users> selectList(){
        List<Users> usersList = new ArrayList<>();
        return usersList=userService.selectList();
    }

    //搜索
    @PostMapping("/select")
    public List<Users> select(@RequestBody Users users){
        String name = users.getName();
        if(StringUtils.isEmpty(name)){
            return null;
        }
        //查询
        List<Users> usersList = new ArrayList<>();
        usersList=userService.select(name);
        System.out.println(usersList);
        return usersList;
    }
    //查询分页
    @PostMapping("selectlimit")
    public List<JSONObject> selectlimit(@RequestBody Users users,@RequestParam("pagenum") int pagenum){
         Integer id = users.getId();
         if(id==null){
             return new ArrayList<>();
         }
         //page num 必传字段
        if (pagenum <= 0) {
            return new ArrayList<>();
        }
        List<Users> usersList= userService.selectlimit(users,pagenum,PAGE_SIZE);
        //转换成object类型
       List<JSONObject> objects= usersList.stream().map(user ->{
           JSONObject object = new JSONObject();
           object.put("200","成功");
           object.put("user",user);
            return object;
       }).collect(Collectors.toList());

        return objects;

    }

    //导出excel导出列表
    @GetMapping("/test")
    @ResponseBody
    public void  test(HttpServletResponse response) throws IOException {
        List<Users> list = new ArrayList<>();
        List<Users> usersList = userService.selectList();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition","attachment; filename=" + "test.xlsx");
        easyutil.writerExcel(response,usersList);

    }
    @GetMapping("/selectList1")
    @ResponseBody
    public void  exportExcel(HttpServletResponse response) throws IOException {
        ExcelWriter writer = null;
        OutputStream outputStream = response.getOutputStream();
        try {
            //添加响应头信息
            response.setHeader("Content-disposition", "attachment; filename=" + "catagory.xls");
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma", "No-cache");//设置头
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头

            //实例化 ExcelWriter
            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);

            //实例化表单
            Sheet sheet = new Sheet(1, 0, Catagory.class);
            sheet.setSheetName("目录");

            //获取数据

            List<Users> usersList = userService.selectList();

            //输出
            writer.write(usersList, sheet);
            writer.finish();
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //导入excel
    // excel导入
    @RequestMapping("/export")
    public String export(@RequestParam("file") MultipartFile file,
                       HttpServletRequest request, HttpServletResponse response) {

        try {
            // @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件
            // 1.创建workbook对象，读取整个文档
            System.out.println();
            if(file==null){
                //返回你的错误状态码
                return "1001";
            }
            String[] fileName = file.getOriginalFilename().split("\\.");
            if(fileName!=null&&fileName.length>0){
                String type = fileName[fileName.length-1];
                //你需要校验的文件类型(后缀)
                System.out.println(type);
                if( !"xls".equals(type) && !"xlsx".equals(type) ){
                    //返回你的错误状态码
                    return "1001";
                }
            }
                InputStream inputStream = file.getInputStream();
//            POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
                Workbook wb = WorkbookFactory.create(inputStream);

//            HSSFWorkbook wb = new HSSFWorkbook(poifsFileSystem);
//             2.读取页脚sheet
                org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);

                // 3.循环读取某一行
                for (Row row : sheet) {
                    // 4.读取每一行的单元格
                    //获取单元格
                    XSSFCell cell = (XSSFCell) row.getCell(0);
                    //设置单元格类型
                    cell.setCellType(CellType.STRING);
                    //获取单元格数据
                    String cellValue = cell.getStringCellValue();
//                String stringCellValue = row.getCell(0).getStringCellValue(); // 第一列数据
                    String stringCellValue2 = row.getCell(1).getStringCellValue();
                  // 第二列
                    // 写多少个具体看大家上传的文件有多少列.....
                    // 测试是否读取到数据,及数据的正确性
                    System.out.println(cell);
                    System.out.println(cellValue);
                    System.out.println(stringCellValue2);
                }


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return  "200";

    }

}













